package xjtu.se.articlecommunity.user.publisharticle;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xjtu.se.articlecommunity.common.CommonService;
import xjtu.se.articlecommunity.common.Result;
import xjtu.se.articlecommunity.common.TokenUtils;
import xjtu.se.articlecommunity.common.dto.CurrentUser;
import xjtu.se.articlecommunity.user.publisharticle.dto.ImgDto;
import xjtu.se.articlecommunity.user.publisharticle.dto.ImgResultDto;
import xjtu.se.articlecommunity.user.publisharticle.dto.PublishDto;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user/publish")
public class PublishAPI {
    @Resource
    private PublishService publishService;

    @Resource
    CommonService commonService;

    /**
     *
     * @param token tokem
     * @param dto   接收发布文章信息的类
     * @return  返回发布成功信息
     */
    @PostMapping("")
    public Result publishArticle(@RequestHeader("Token") String token, @RequestBody PublishDto dto){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        dto.setU_id(currentUser.getU_id());
        publishService.publishArticle(dto);
        return Result.success("发布成功！");
    }


    @ResponseBody
    @PostMapping("/uploadImg")
    //RequestParam中的属性名称要和前端定义的一致．所以写"img"
    //使用List<MultipartFile>进行接收
    //返回的是一个Ｄto类，后面会说明，使用@ResponseBody会将其转换为Json格式数据
    // 上传图片先保存到用户id下，当点击发布文章时，再把图片中的文章id更新，主要是在编辑文章时不知道正在编辑的文章的id
    public Result uploadEditorImg(@RequestParam("img") List<MultipartFile> list, ImgResultDto imgResultDto, ImgDto imgDto, PublishDto publishDto) {
        //服务曾处理数据，返回Dto
        try{
            publishService.uploadImg(imgDto, imgResultDto, list, publishDto);
            return Result.success("上传成功", imgResultDto);
        }
        catch (Exception e){
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_BUSINESS, "上传失败！");
        }
    }

    /**
     *
     * @param a_id 文章id
     * @return 返回需要编辑的文章信息
     */
    @GetMapping("/getPublishedAriticle/{a_id}")
    public Result getPublishedArticle(@PathVariable String a_id){
        PublishDto publishedArticle=publishService.getPublishedArticle(a_id);
        return Result.success(publishedArticle);
    }

    @PostMapping("/edit/{a_id}")
    public Result editArticle(@RequestHeader("Token") String token, @RequestBody PublishDto dto, @PathVariable String a_id){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        dto.setU_id(currentUser.getU_id());
        dto.setA_id(a_id);

       for(String s:dto.getTabs()) {
           System.out.println("dto:" + s);
        }

        publishService.rePublishArticle(dto);
        return Result.success("重新发布成功！");
    }


}
